package com.wakala.employment.activity;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;

import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.AMap.InfoWindowAdapter;
import com.amap.api.maps2d.AMapUtils;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.NaviPara;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.poisearch.PoiSearch.OnPoiSearchListener;
import com.hjq.toast.Toaster;
import com.kongzue.dialogx.dialogs.CustomDialog;
import com.kongzue.dialogx.interfaces.OnBindView;
import com.lljjcoder.Interface.OnCityItemClickListener;
import com.lljjcoder.bean.CityBean;
import com.lljjcoder.bean.DistrictBean;
import com.lljjcoder.bean.ProvinceBean;
import com.lljjcoder.style.cityjd.JDCityConfig;
import com.lljjcoder.style.cityjd.JDCityPicker;
import com.wakala.employment.R;
import com.wakala.employment.adapter.bean.PoiEntity;
import com.wakala.employment.adapter.poi.PoiListAdapter;
import com.wakala.employment.utils.AMapUtil;
import com.wakala.employment.utils.ToastUtil;
import com.xuexiang.xui.utils.DensityUtils;
import com.xuexiang.xui.utils.ThemeUtils;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.alpha.XUIAlphaTextView;
import com.xuexiang.xui.widget.textview.supertextview.SuperButton;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.common.logger.Logger;
import com.xuexiang.xutil.net.JsonUtil;
import com.xuexiang.xutil.tip.ToastUtils;
import com.yangbin.util.StatusBarHelper;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class AddressMapActivity extends FragmentActivity implements
        AMap.OnMarkerClickListener, InfoWindowAdapter, TextWatcher,
        OnPoiSearchListener, OnClickListener, Inputtips.InputtipsListener {

    private static String TAG="AddressMapActivity";

    //---------------定位-----
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new MyAMapLocationListener();
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    private SuperButton ssBtnRegion;

    //------------------------
    private  XUIAlphaTextView tvMyAddress;
    //----------------

    private AMap aMap;
    private MapView mapView;
    private final static LatLng SYDNEY = new LatLng(-33.86759, 151.2088);
    private final static LatLng BEIJING = new LatLng(39.8965, 116.4074);

    private AutoCompleteTextView searchText;// 输入搜索关键字
    private String keyWord = "";// 要输入的poi搜索关键字
    private ProgressDialog progDialog = null;// 搜索时进度条
    private CustomDialog customDialog = null;//搜索市等待对话框
    //private EditText editCity;// 要输入的城市名字或者城市区号
    private String editCity="";
    private PoiResult poiResult; // poi返回的结果
    private int currentPage = 0;// 当前页面，从0开始计数
    private PoiSearch.Query query;// Poi查询条件类
    private PoiSearch poiSearch;// POI搜索
    //---

    private Boolean  searched = false;


    private RecyclerView recyclerView;
    private PoiListAdapter mPoiListAdapter;

    private List<PoiEntity> poiEntityList = new ArrayList<>();

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address_map);
        StatusBarHelper.setStatusBarLightMode(this);
        getWindow().setStatusBarColor(getResources().getColor(R.color.white));
        tvMyAddress = (XUIAlphaTextView)findViewById(R.id.tv_my_address);
        ssBtnRegion = findViewById(R.id.ssBtn_region);
        ssBtnRegion.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                //mLocationClient.startLocation();
                //customDialog.show();
                //打开城市选择器
                showCityPicker();
            }
        });

        mapView = (MapView) findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        String sha1 = sHA1(this);
        init();
        initLocation();
        //----
        initListView();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPoiListAdapter.recycle();
    }

    //----------------
    private void initListView(){
        recyclerView = findViewById(R.id.recyclerView);
        WidgetUtils.initRecyclerView(recyclerView, DensityUtils.dp2px(this, 5), ThemeUtils.resolveColor(this, R.attr.xui_config_color_background));

        recyclerView.setAdapter(mPoiListAdapter = new PoiListAdapter(false));
        mPoiListAdapter.setOnItemClickListener((itemView, item, position) -> {
            //Toaster.show(item.getAdName());
            Intent intent = new Intent();
            intent.putExtra("poiEntity", JsonUtil.toJson(item));
            setResult(101,intent);
            finish();
        });
    }
    //---------------------------
    /**
     * 初始化AMap对象
     */
    private void init() {
        if (aMap == null) {
            aMap = mapView.getMap();
            setUpMap();
        }
        //初始化加载等待对话框
        customDialog = CustomDialog.build()
                .setCustomView(new OnBindView<CustomDialog>(R.layout.dialog_layout_spinkit) {
                    @Override
                    public void onBind(final CustomDialog dialog, View v) {
                    }
                });
    }

    private void initLocation() {
        //初始化定位
        try {
            AMapLocationClient.updatePrivacyShow(this, true, true);
            AMapLocationClient.updatePrivacyAgree(this, true);
            mLocationClient = new AMapLocationClient(getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //获取一次定位结果：
        //该方法默认为false。
        mLocationOption.setOnceLocation(false);

        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(true);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
        customDialog.show();
    }


    /**
     * 高德定位监听
     */
    private class MyAMapLocationListener implements AMapLocationListener {

        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            customDialog.dismiss();
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    Log.e(TAG+"-位置：", aMapLocation.getAddress());
                    String address = aMapLocation.getAddress();
                    String city = aMapLocation.getCity();
                    String cityCode = aMapLocation.getCityCode();
                    String locationDetail= aMapLocation.getLocationDetail();
                    //editCity.setText(aMapLocation.getCity());
                    editCity = aMapLocation.getCity();
                    tvMyAddress.setText(address);
                    ssBtnRegion.setText(city);
                    mLocationClient.stopLocation();
                    //定位完成后搜索当前定位的POI
                    try {
                        poiSearch(aMapLocation.getLongitude(),aMapLocation.getLatitude(),100);
                    } catch (AMapException e) {
                        Toaster.show(e.getMessage());
                    }

                } else {
                    Toaster.show("定位失败");
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    String error="location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo();
                    Log.e("AmapError", "location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());
                }
            }
        }
    }

    public static String sHA1(Context context){
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            String result = hexString.toString();
            return result.substring(0, result.length()-1);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 设置页面监听
     */
    private void setUpMap() {
        Button searButton = (Button) findViewById(R.id.searchButton);
        searButton.setOnClickListener(this);
        Button nextButton = (Button) findViewById(R.id.nextButton);
        nextButton.setOnClickListener(this);
        Button exitButton = findViewById(R.id.exitButton);
        exitButton.setOnClickListener(this);
        searchText = (AutoCompleteTextView) findViewById(R.id.keyWord);
        searchText.addTextChangedListener(this);// 添加文本输入框监听事件
        aMap.setOnMarkerClickListener(this);// 添加点击marker监听事件
        aMap.setInfoWindowAdapter(this);// 添加显示infowindow监听事件
        //

        AMapLocationClient.updatePrivacyShow(this, true, true);
        AMapLocationClient.updatePrivacyAgree(this, true);


    }

    /**
     * 点击搜索按钮
     */
    public void searchButton() throws AMapException {
        keyWord = AMapUtil.checkEditText(searchText);
        if ("".equals(keyWord)) {
            ToastUtils.toast("请输入搜索关键字");
        } else {
            doSearchQuery(keyWord);
        }
    }

    /**
     * 点击下一页按钮
     */
    public void nextButton() {
        if (query != null && poiSearch != null && poiResult != null) {
            if (poiResult.getPageCount() - 1 > currentPage) {
                currentPage++;
                query.setPageNum(currentPage);// 设置查后一页
                poiSearch.searchPOIAsyn();
                customDialog.show();//显示等待对话框
            } else {
                ToastUtil.show(AddressMapActivity.this,
                        "没有结果");
            }
        }
    }

    /**
     * 显示进度框
     */
    private void showProgressDialog() {
        if (progDialog == null)
            progDialog = new ProgressDialog(this);
        progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progDialog.setIndeterminate(false);
        progDialog.setCancelable(false);
        progDialog.setMessage("正在搜索:\n" + keyWord);
        progDialog.show();
    }

    /**
     * 隐藏进度框
     */
    private void dissmissProgressDialog() {
        if (progDialog != null) {
            progDialog.dismiss();
        }
    }

    /**
     * 开始进行poi搜索
     */
    protected void doSearchQuery(String keyWord) throws AMapException {
        //showProgressDialog();// 显示进度框
        customDialog.show();//显示等待对话框
        currentPage = 0;
        query = new PoiSearch.Query(keyWord, "", editCity);// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        query.setPageSize(10);// 设置每页最多返回多少条poiitem
        query.setPageNum(currentPage);// 设置查第一页
        query.setCityLimit(true);
        query.setExtensions(PoiSearch.EXTENSIONS_ALL);

        poiSearch = new PoiSearch(this, query);
        poiSearch.setOnPoiSearchListener(this);
        poiSearch.searchPOIAsyn();
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        marker.showInfoWindow();
        return false;
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    @Override
    public View getInfoWindow(final Marker marker) {
       /* View view = getLayoutInflater().inflate(R.layout.poikeywordsearch_uri, null);
        TextView title = (TextView) view.findViewById(R.id.title);
        title.setText(marker.getTitle());

        TextView snippet = (TextView) view.findViewById(R.id.snippet);
        snippet.setText(marker.getSnippet());
        ImageButton button = (ImageButton) view
                .findViewById(R.id.start_amap_app);
        // 调起高德地图app
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startAMapNavi(marker);
            }
        });
        return view;*/
        return null;
    }

    /**
     * 调起高德地图导航功能，如果没安装高德地图，会进入异常，可以在异常中处理，调起高德地图app的下载页面
     */
    public void startAMapNavi(Marker marker) {
        // 构造导航参数
        NaviPara naviPara = new NaviPara();
        // 设置终点位置
        naviPara.setTargetPoint(marker.getPosition());
        // 设置导航策略，这里是避免拥堵
        naviPara.setNaviStyle(AMapUtils.DRIVING_AVOID_CONGESTION);

        // 调起高德地图导航
        try {
            AMapUtils.openAMapNavi(naviPara, getApplicationContext());
        } catch (com.amap.api.maps2d.AMapException e) {

            // 如果没安装会进入异常，调起下载页面
            AMapUtils.getLatestAMapApp(getApplicationContext());

        }

    }

    /**
     * 判断高德地图app是否已经安装
     */
    public boolean getAppIn() {
        PackageInfo packageInfo = null;
        try {
            packageInfo = this.getPackageManager().getPackageInfo(
                    "com.autonavi.minimap", 0);
        } catch (NameNotFoundException e) {
            packageInfo = null;
            e.printStackTrace();
        }
        // 本手机没有安装高德地图app
        if (packageInfo != null) {
            return true;
        }
        // 本手机成功安装有高德地图app
        else {
            return false;
        }
    }

    /**
     * 获取当前app的应用名字
     */
    public String getApplicationName() {
        PackageManager packageManager = null;
        ApplicationInfo applicationInfo = null;
        try {
            packageManager = getApplicationContext().getPackageManager();
            applicationInfo = packageManager.getApplicationInfo(
                    getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            applicationInfo = null;
        }
        String applicationName = (String) packageManager
                .getApplicationLabel(applicationInfo);
        return applicationName;
    }

    /**
     * poi没有搜索到数据，返回一些推荐城市的信息
     */
    private void showSuggestCity(List<SuggestionCity> cities) {
        String infomation = "推荐城市\n";
        for (int i = 0; i < cities.size(); i++) {
            infomation += "城市名称:" + cities.get(i).getCityName() + "城市区号:"
                    + cities.get(i).getCityCode() + "城市编码:"
                    + cities.get(i).getAdCode() + "\n";
        }
        ToastUtil.show(AddressMapActivity.this, infomation);

    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
                                  int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        String newText = s.toString().trim();
        if (!AMapUtil.IsEmptyOrNullString(newText)) {
            InputtipsQuery inputquery = new InputtipsQuery(newText, editCity);
            Inputtips inputTips = new Inputtips(AddressMapActivity.this, inputquery);
            inputTips.setInputtipsListener(this);
            inputTips.requestInputtipsAsyn();
        }
    }


    /**
     * POI信息查询回调方法
     */
    @Override
    public void onPoiSearched(PoiResult result, int rCode) {
        //dissmissProgressDialog();// 隐藏对话框
        customDialog.dismiss();//隐藏等待对话框
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getQuery() != null) {// 搜索poi的结果
                if (result.getQuery().equals(query)) {// 是否是同一条
                    poiResult = result;
                    // 取得搜索到的poiitems有多少页
                    List<PoiItem> poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
                    List<SuggestionCity> suggestionCities = poiResult
                            .getSearchSuggestionCitys();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息

                    if (poiItems != null && poiItems.size() > 0) {
                        aMap.clear();// 清理之前的图标
                        PoiOverlay poiOverlay = new PoiOverlay(aMap, poiItems);
                        poiOverlay.removeFromMap();
                        poiOverlay.addToMap();
                        poiOverlay.zoomToSpan();
                        //将POI信息提交给listView的adapter
                        copyPoiItem2PoiEntity(poiItems,poiEntityList);
                        mPoiListAdapter.resetDataSource(poiEntityList);
                        mPoiListAdapter.refresh(poiEntityList);
                        mPoiListAdapter.notifyDataSetChanged();
                    } else if (suggestionCities != null
                            && suggestionCities.size() > 0) {
                        showSuggestCity(suggestionCities);
                    } else {
                        ToastUtil.show(AddressMapActivity.this,
                                "没有结果");
                    }
                }
            } else {
                ToastUtil.show(AddressMapActivity.this,
                        "没有结果");
            }
        } else {
            ToastUtil.showerror(AddressMapActivity.this, rCode);
        }

    }

    @Override
    public void onPoiItemSearched(PoiItem item, int rCode) {
        // TODO Auto-generated method stub

    }

    private void copyPoiItem2PoiEntity(List<PoiItem> poiItemList, List<PoiEntity> poiEntityList){
        poiEntityList.clear();
        for (PoiItem poiItem:poiItemList){

            String cityName = poiItem.getCityName();
            String provinceName = poiItem.getProvinceName();
            String adName = poiItem.getAdName();
            PoiEntity poiEntity = new PoiEntity(poiItem.getTitle(),provinceName+cityName+adName+poiItem.getSnippet());
            poiEntity.setAdCode(poiItem.getAdCode());
            poiEntity.setAdName(poiItem.getAdName());
            poiEntity.setProvinceCode(poiItem.getProvinceCode());
            poiEntity.setProvinceName(poiItem.getProvinceName());
            poiEntity.setCityCode(poiItem.getCityCode());
            poiEntity.setCityName(poiItem.getCityName());
            if(null!=poiItem.getLatLonPoint()){
                poiEntity.setLat(poiItem.getLatLonPoint().getLatitude()+"");
                poiEntity.setLon(poiItem.getLatLonPoint().getLongitude()+"");
            }
            poiEntity.setSnippet(poiItem.getSnippet());
            poiEntityList.add(poiEntity);
        }
    }

    /**
     * 周边搜索 根据经纬度 及距离范围
     */
    private void poiSearch(double longitude, double latitude, int distances) throws AMapException {
        customDialog.show();
        LatLonPoint point=new LatLonPoint(latitude,longitude);
        GeocodeSearch geocodeSearch=new GeocodeSearch(this);
        RegeocodeQuery regeocodeQuery=new RegeocodeQuery(point,distances,geocodeSearch.AMAP);
        geocodeSearch.getFromLocationAsyn(regeocodeQuery);
        geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int rCode) {
                customDialog.dismiss();
               // log.d(rCode);
                if (1000==rCode){
                    RegeocodeAddress address=regeocodeResult.getRegeocodeAddress();
                    StringBuffer stringBuffer=new StringBuffer();
                    String area = address.getProvince();//省或直辖市
                    editCity = address.getCity();//地级市或直辖市
                    String subLoc = address.getDistrict();//区或县或县级市
                    List<PoiItem> pois = address.getPois();//获取周围兴趣点
                    Logger.d("地区="+area);
                    copyPoiItem2PoiEntity(pois,poiEntityList);
                    mPoiListAdapter.refresh(poiEntityList);
                    mPoiListAdapter.notifyDataSetChanged();
                    //poiAdapter.refreshDatas(pois);
                    //cameraMarkers(regeocodeResult.getRegeocodeQuery().getPoint().getLatitude(),regeocodeResult.getRegeocodeQuery().getPoint().getLongitude());
                }else {
                    Toaster.show("POI查询异常");
                }
            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int rCode) {
                //Logger.d(rCode);
               // Logger.d(geocodeResult.getGeocodeAddressList());
               // Logger.d(geocodeResult.getGeocodeQuery());
            }
        });

    }

    /**
     * Button点击事件回调方法
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            /**
             * 点击搜索按钮
             */
            case R.id.searchButton:
                try {
                    searchButton();
                    searched = true;
                } catch (AMapException e) {
                    Log.e(TAG,e.getErrorMessage());
                    Toaster.show(e.getMessage());
                }
                break;
            /**
             * 点击下一页按钮
             */
            case R.id.nextButton:
                if(searched){
                    nextButton();
                }else {
                    try {
                        searchButton();
                        searched = true;
                    } catch (AMapException e) {
                        Log.e(TAG,e.getErrorMessage());
                        Toaster.show(e.getMessage());
                    }
                }
                break;
            case  R.id.exitButton:
                finish();
                break;
            default:
                break;
        }
    }



    @Override
    public void onGetInputtips(List<Tip> tipList, int rCode) {
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {// 正确返回
            List<String> listString = new ArrayList<String>();
            for (int i = 0; i < tipList.size(); i++) {
                listString.add(tipList.get(i).getName());
            }
            ArrayAdapter<String> aAdapter = new ArrayAdapter<String>(
                    getApplicationContext(),
                    R.layout.route_inputs, listString);
            searchText.setAdapter(aAdapter);
            aAdapter.notifyDataSetChanged();
        } else {
            ToastUtil.showerror(AddressMapActivity.this, rCode);
        }


    }

    /**
     * 显示省市区选择组件
     */
    private void showCityPicker() {
        //创建对象
        JDCityPicker cityPicker = new JDCityPicker();
        //初始化配置
        JDCityConfig jdCityConfig = new JDCityConfig.Builder().build();
        //设置显示的样式
        jdCityConfig.setShowType(JDCityConfig.ShowType.PRO_CITY);
        cityPicker.init(this);//初始化选择器
        cityPicker.setConfig(jdCityConfig);
        cityPicker.setOnCityItemClickListener(new OnCityItemClickListener() {
            @Override
            public void onSelected(ProvinceBean province,
                                   CityBean city, DistrictBean district) {//选中后的监听
                String cityName = city.getName();
                if (city.getName().equals("市辖区")) {
                    cityName = province.getName();
                }
                ssBtnRegion.setText(cityName);
                editCity = cityName;
                keyWord = AMapUtil.checkEditText(searchText);
                if(!StringUtils.isEmpty(keyWord)){
                    try {
                        doSearchQuery(keyWord);
                    } catch (AMapException e) {
                        Log.e(TAG,e.getErrorMessage());
                    }
                }
            }

            @Override
            public void onCancel() {
                //cancel监听
            }
        });
        //显示地区列表
        cityPicker.showCityPicker();
    }
}